from django.shortcuts import render
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect
from .. models import Goods,Types
from django.urls import reverse
from . views import uploads
from . typeviews import GetTypesAll
# Create your views here.

#商品添加
def goodsadd(request):

    

    context = {'glist':GetTypesAll()}
    return render(request,'admin/goods/add.html',context)


#执行添加
def goodsinsert(request):

    if not request.FILES.get('pic',None):
        return HttpResponse('<script>alert("请选择上传的商品图片");location.href="'+reverse('admin_goods_add')+'"</script>')
    try:
        ob= Goods()
        ob.typeid = Types.objects.get(id=request.POST['typeid'])
        ob.title = request.POST['title']
        ob.price = request.POST['price']
        ob.storage = request.POST['storage']
        ob.info = request.POST['info']
        ob.pic = uploads(request) 
        ob.save()

        import os
        os.remove('/home/yc/py9xm/web/'+request.POST['picurl'])

        return HttpResponse('<script>alert("添加成功");location.href="/admin/goods/list"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="/admin/goods/add/"</script>')



#商品列表
def goodslist(request):
    #搜索条件
    types = request.GET.get('type',None)

    #搜索参数
    keywords = request.GET.get('keywords','') 

    #状态搜索的定义
    statuslist={'下架':0,'新品':1,'热卖':2}

    if types:
        # 有搜索条件
        #如果搜索类型为all,则为多字段单参数

        if types=='all':
            from django.db.models import Q

            data = Goods.objects.filter(Q(title__contains=keywords)|Q(storage__contains=keywords)|Q(price__contains=keywords)|Q(status__contains=statuslist.get(keywords,'aa')))

        elif types=='title':
            data = Goods.objects.filter(title__contains=keywords)
        
        elif types=='storage':
            data = Goods.objects.filter(storage__contains=keywords)

        elif types=='price':
            data = Goods.objects.filter(price__contains=keywords)

        elif types=='status':
            data = Goods.objects.filter(status__contains=statuslist.get(keywords,'aaa'))
        elif types =='typeid':
            if keywords:
                obj = Types.objects.filter(name__contains=keywords)
                for x in obj:
                    print(x.id)
                    data = Goods.objects.filter(typeid=x.id).exclude(status=3)
            else:
                data= Goods.objects.exclude(status=3)

    else:
        #没有搜索添加显示全部
        data = Goods.objects.exclude(status=3)


    #数据分页类
    from django.core.paginator import Paginator

    #实例化分类页 参数1查询的数据 参数2 每页显示的数据
    paginator = Paginator(data,10)


    #当前页码
    p= int(request.GET.get('p',1))

    #根据当前页码获取当前页显示的数据
    goodslist=paginator.page(p)

    #获取当前页的页码数
    # num = paginator.page_range


    #分配数据
    context = {'glist':goodslist,}
    #返回页面
    return render(request,'admin/goods/list.html',context)


#修改
def goodsedit(request,uid):
    # 查询用户信息
    ob = Goods.objects.get(id=uid)
    

    typename = ob.typeid.name
    tob = Types.objects.filter(name = typename)

    from django.utils.html import format_html
    txt =  format_html(ob.info)
    ob.info  = txt


    context = {'ginfo':ob,'tlist':tob}
    return render(request,'admin/goods/edit.html',context)




# 执行修改
def goodsupdate(request):
    import os
    try:
        # 根据id获取用户对象
        ob = Goods.objects.get(id=request.POST['id'])
        ob.title = request.POST['title']
        ob.price = request.POST['price']
        ob.storage = request.POST['storage']
        ob.info = request.POST['info']

        if request.FILES.get('pic'):
            if ob.pic == request.POST.get('pic'):
                pass
            else:
                # import os
                # # 从数据库中删除原头像
                os.remove('.'+ob.pic)
                ob.pic = uploads(request)
        if request.POST.get('picurl',None):
            import os
            os.remove('/home/yc/py9xm/web/'+request.POST['picurl'])
        ob.save()
        return HttpResponse('<script>alert("修改成功");location.href="/admin/goods/list/"</script>')
    except:
        return HttpResponse('<script>alert("修改失败");location.href="/admin/goods/edit/'+str(ob.id)+'"</script>')

#修改状态
def goodsstatus(request):

    # 执行状态修改
    ob = Goods.objects.get(id=request.GET['uid'])
    ob.status = int(request.GET['status'])
    ob.save()

    return HttpResponse('')


# 执行用户删除
def goodsdel(request):
    ob = Goods.objects.get(id=request.GET['gid'])
    ob.status = 3
    ob.save()

    return HttpResponse('ok')

